package com.cg.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.RemoteTokenServices;
import org.springframework.security.oauth2.provider.token.ResourceServerTokenServices;
import org.springframework.security.oauth2.provider.token.TokenStore;

@Configuration
@EnableResourceServer   //标识属于oauth2的资源服务
public class MyResourceServerConfig extends ResourceServerConfigurerAdapter {

    public static final String RESOURCE_SALARY = "salary";

    @Autowired
    private TokenStore tokenStore;

    /**
     * tokenServices: ResourceServerTokenServices类的实例，用来实现令牌服务，即如何验证令牌
     * tokenStore: TokenStore类的实例，指定令牌如何访问，与tokenServices配置可选
     * resourceId: 这个资源服务的ID，是可选的。但推荐设置并在授权服务中进行验证
     * 其他的扩展属性例如tokenExtractor令牌提取器用来提取请求中的令牌
     */
    @Override
    public void configure(ResourceServerSecurityConfigurer resources) {
        resources.resourceId(RESOURCE_SALARY)   //资源id
//                .tokenServices(tokenServices()) //使用远程服务验证令牌
                .tokenStore(tokenStore) //基于jwt token配置
                .stateless(true);   //无状态模式
    }

    //配置access_token远程验证策略
    public ResourceServerTokenServices tokenServices(){
        RemoteTokenServices services = new RemoteTokenServices();
        services.setCheckTokenEndpointUrl("http://localhost:53020/uaa/oauth/check_token");  //uaa授权服务验证token合法性
        services.setClientId("c1");
        services.setClientSecret("secret");
        return services;
    }

    /**
     * authorizeRequests()方法验证请求。anyMatchers方法匹配访问路径。access方法配置需要的权限
     * sessionManagement方法配置session管理策略
     * 其他自定义权限保护规则也通过HttpSecurity来配置
     */
    @Override
    public void configure(HttpSecurity http) throws Exception { //配置安全策略
        http.authorizeRequests()
                .antMatchers("/salary/**").access("#oauth2.hasScope('all')")
                .antMatchers("/other/**").denyAll()
                .anyRequest().authenticated()
                .and().csrf().disable()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
    }
}
